package pl.com.hme.kody.pocztowe.service;

import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;

import pl.com.hme.kody.pocztowe.http.HttpClientFactory;
import pl.com.hme.kody.pocztowe.parser.PocztaXmlParser;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import android.webkit.WebView;

public class CodeQueryService extends ContinuousIntentService {

	private static final String TAG = "CodeQueryService";

	private int mStatus = STATUS_NOT_STARTED;
	private HttpClient mHttpClient;
	private ResultReceiver mReceiver;

	public static final String EXTRA_BUNDLE_POI_SET = "pl.com.hme.kody.pocztowe.extra.BUNDLE_POI";
	public static final String EXTRA_STATUS_RECEIVER = "pl.com.hme.kody.pocztowe.extra.STATUS_RECEIVER";
	public static final String EXTRA_COMMAND_STRING = "pl.com.hme.kody.pocztowe.extra.COMMAND_STRING";
	public static final String EXTRA_QUERY_CITY = "pl.com.hme.kody.pocztowe.extra.QUERY_CITY";
	public static final String EXTRA_QUERY_STREET = "pl.com.hme.kody.pocztowe.extra.QUERY_STREET";

	public static final int STATUS_NOT_STARTED = 0x1;
	public static final int STATUS_STARTED = 0x2;
	public static final int STATUS_ERROR = 0x3;
	public static final int STATUS_CONNECTING = 0x4;
	public static final int STATUS_XML_PARSING = 0x5;

	public static final int COMMAND_GET_STATUS = 0x1;
	public static final int COMMAND_GET_POI_SET = 0x2;
	public static final int COMMAND_START_SERVICE = 0x3;
	public static final int COMMAND_STOP_SERVICE = 0x4;

	public CodeQueryService() {
		super(TAG);
	}

	@Override
	public void onCreate() {
		super.onCreate();

		WebView webView = new WebView(this);
		String userAgent = webView.getSettings().getUserAgentString();
		webView = null;

		mHttpClient = HttpClientFactory.getHttpClient(userAgent);
	}

	@Override
	protected void onHandleIntent(Intent intent, int startId) {
		if (intent != null) {
			mReceiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		}else{
			mReceiver = null;
			return;
		}

		int command = intent.getIntExtra(EXTRA_COMMAND_STRING, 0x0);

		if (mStatus != STATUS_ERROR) {

			try {

				switch (command) {
				case COMMAND_START_SERVICE:
					initializeConnection();

					break;
				case COMMAND_GET_POI_SET:
					if (mStatus == STATUS_NOT_STARTED) {
						initializeConnection();
					}
					sendCurrentStatus();

					mStatus = STATUS_CONNECTING;
					sendCurrentStatus();

					InputStream inputStream = HttpQueryMaker.getCodeFromCityAndStreet(intent
							.getStringExtra(EXTRA_QUERY_CITY), intent.getStringExtra(EXTRA_QUERY_STREET), mHttpClient);

					if (inputStream != null) {
						mStatus = STATUS_XML_PARSING;
						sendCurrentStatus();

						PocztaXmlParser.parseXml(inputStream);

					} else {
						throw new Exception("No inputStream!");
					}

					break;
				case COMMAND_GET_STATUS:
					sendCurrentStatus();

					break;
				case COMMAND_STOP_SERVICE:
					// stopSelf(startId);
					break;

				}

			} catch (Exception e) {
				mStatus = STATUS_ERROR;

				Log.w(TAG, e);

				if (mReceiver != null) {
					Bundle bundle = new Bundle();
					bundle.putString(Intent.EXTRA_TEXT, e.toString());
					mReceiver.send(STATUS_ERROR, bundle);
				}
			}
		} else {
			sendCurrentStatus();
		}
	}

	private void initializeConnection() throws Exception {
		HttpResponse httpResponse = HttpQueryMaker.getDummyIndexPage(mHttpClient);

		int status = httpResponse.getStatusLine().getStatusCode();

		if (status != HttpStatus.SC_OK) {
			throw new Exception("Unexpected server response " + httpResponse.getStatusLine());
		} else {
			mStatus = STATUS_STARTED;
		}
	}

	private void sendCurrentStatus() {
		if (mReceiver != null) {
			mReceiver.send(mStatus, Bundle.EMPTY);
		}
	}
}
